// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-2ga6780q302b7f4a' // 使用正确的环境ID
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID
  
  try {
    // 查找用户是否存在
    const { data: users } = await db.collection('users').where({
      openId: openId
    }).get()
    
    let user = null
    
    if (users.length === 0) {
      // 新用户，创建用户记录
      const { userInfo } = event
      const result = await db.collection('users').add({
        data: {
          openId: openId,
          nickName: userInfo.nickName || '微信用户',
          avatarUrl: userInfo.avatarUrl,
          creditScore: 100, // 初始信用分
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
      
      // 获取新创建的用户信息
      const { data: newUser } = await db.collection('users').doc(result._id).get()
      user = newUser
    } else {
      // 更新用户信息
      user = users[0]
      if (event.userInfo && event.userInfo.nickName) {
        await db.collection('users').doc(user._id).update({
          data: {
            nickName: event.userInfo.nickName,
            avatarUrl: event.userInfo.avatarUrl,
            updateTime: db.serverDate()
          }
        })
        
        // 更新本地 user 对象
        user.nickName = event.userInfo.nickName
        user.avatarUrl = event.userInfo.avatarUrl
      }
    }
    
    return {
      code: 0,
      data: {
        openId: openId,
        userInfo: {
          nickName: user.nickName,
          avatarUrl: user.avatarUrl,
          creditScore: user.creditScore
        }
      },
      message: '登录成功'
    }
  } catch (err) {
    return {
      code: -1,
      data: null,
      message: '登录失败: ' + err.message
    }
  }
} 